<template>
  <div class="app-speck">
    <div class="speck-box">
      <div class="speck-box-tab">
        <img class="avatar" src="@/assets/image/2.jpg" alt="" />
        <div class="tab-box">
          <div
            class="tab-item"
            style="margin-top: 10px"
            v-for="item in tabList"
            :key="item.name"
            @click="changeTab(item.name)"
          >
            <img
              style="width: 35px; height: 35px"
              :src="require(`@/assets/image/${item.url}.png`)"
              v-if="activename != item.name"
            />
            <img
              style="width: 35px; height: 35px"
              :src="require(`@/assets/image/${item.active}.png`)"
              v-else
            />
            <div
              class="msgicon"
              v-if="item.allunread > 0 && item.name == 'msg'"
            >
              {{ item.allunread }}
            </div>
            <div class="msgicon" v-if="appunread > 0 && item.name == 'people'">
              {{ appunread }}
            </div>
          </div>
        </div>
      </div>
      <div class="speck-box-list">
        <div class="speck-box-list-top">
          <div
            class="speck-box-list-top-title"
            style="display: flex; align-items: center"
          >
            <div style="width: 200px height: 30px;position: relative;">
              <img
                style="
                  width: 20px;
                  height: 20px;
                  position: absolute;
                  top: 5px;
                  left: 8px;
                  z-index: 20;
                "
                src="@/assets/image/search.png"
                alt=""
              />
              <input
                class="inp"
                style="
                  width: 200px;
                  height: 30px;
                  padding-left: 27px;
                  border-radius: 2px;
                "
              />
            </div>
            <div>
              <img
                style="height: 46px"
                src="@/assets/image/add.png"
                @click="add"
                alt=""
              />
              <div class="add-box"></div>
            </div>
          </div>
        </div>
        <div class="speck-box-list-content">
          <people
            v-show="activename == 'people'"
            :groupList="groupList"
            @expanded="getFriendlist"
            ref="people"
            @changefriend="changefriend"
            @sendmessage="sendmessage"
            @open="openfriendapplication"
          ></people>
          <msg
            v-show="activename == 'msg'"
            :chatList="chatList"
            @changeChat="changeChat"
            ref="msg"
          ></msg>
        </div>
      </div>
      <div class="speck-box-content">
        <div class="speck-nohave" v-show="chatname == ''">
          <img
            style="width: 200px; height: 200px"
            src="../../../public/11.png"
            alt=""
          />
        </div>
        <msgcontent
          v-if="chatname == 'message'"
          :dataObj="msgData"
          :contentone="contentone"
          @send="send"
        ></msgcontent>
        <peoplecontent
          v-if="chatname == 'people'"
          :peopledata="peopledata"
          @sendmessage="sendmessage"
          @changenotes="changenotes"
          @changeGroup="changeGroup"
        >
        </peoplecontent>
        <application
          v-if="chatname == 'friend'"
          ref="application"
          @open="getFriendGroup"
          @getlist="getapplicationlist"
          :list="list"
        >
        </application>
      </div>
    </div>
    <Dialog ref="dialog" title="添加好友" width="300px" height="400px">
      <template #default>
        <div
          style="width: 200px height: 30px;position: relative;display: flex;align-items: center;margin: 0 auto;"
        >
          <img
            style="
              width: 20px;
              height: 20px;
              position: absolute;
              top: 5px;
              left: 8px;
              z-index: 20;
            "
            src="@/assets/image/search.png"
            alt=""
          />
          <input
            class="inp"
            style="
              width: 200px;
              height: 30px;
              padding-left: 27px;
              border-radius: 2px;
            "
            v-model="searchKeyWord"
          />
          <el-button type="primary" @click="search">搜索</el-button>
        </div>
        <div style="width: 100%; height: 100%; overflow: auto">
          <div class="nohave" v-if="friendList.length == 0">
            <el-icon size="50"><Stamp /></el-icon>
            <div>快来发现更多的朋友</div>
          </div>
          <div class="have" v-else>
            <addfriend
              v-for="item in friendList"
              :dataObj="item"
              :key="item.username"
              @send="sendmessage"
              @add="openapplication"
            ></addfriend>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button @click="$refs.dialog.close()" type="primary" size="small"
          >取消</el-button
        >
      </template>
    </Dialog>
    <Dialog
      ref="dialog1"
      :title="openapplicationvalue"
      width="300px"
      height="500px"
      color="#f5f5f5"
    >
      <template #default>
        <div style="padding: 0 10px" class="">
          <div style="display: flex; margin-top: 10px">
            <img class="img" :src="openapplicationobj.avatar" alt="" />
            <div
              style="margin-left: 10px; display: flex; flex-direction: column"
            >
              <div style="margin-top: 5px">
                {{ openapplicationobj.nickname }}
              </div>
              <div>{{ openapplicationobj.username }}</div>
            </div>
          </div>
          <div class="m_b_10 m_t_10">
            <div class="m_b_5 m_l_5 text-1">填写验证信息</div>
            <textarea
              class="textarea"
              v-model="notes"
              cols="33.5"
              rows="5"
            ></textarea>
          </div>
          <div class="m_b_10 m_t_10">
            <div class="m_b_5 m_l_5 text-1">备注</div>
            <textarea
              class="textarea"
              v-model="msg"
              cols="33.5"
              rows="1"
            ></textarea>
          </div>
          <div class="m_b_10 m_t_10">
            <div class="m_b_5 m_l_5 text-1">分组</div>
            <el-select
              v-model="value1"
              placeholder="Select"
              style="width: 100%"
            >
              <el-option
                v-for="item in groupList"
                :key="item.group_id"
                :label="item.group_name"
                :value="item.group_id"
              />
            </el-select>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button @click="addfriend" type="primary" size="small"
          >发送</el-button
        >
        <el-button @click="$refs.dialog1.close()" size="small">取消</el-button>
      </template>
    </Dialog>
  </div>
</template>
<script>
import io from 'socket.io-client'
import people from './component/people.vue'
import msg from './component/msg.vue'
import { getChatList, getChatOne, sendMsg, removeUn, changeChatState, getFriendGroup, getFriendList, addChat, searchFriend, addFriend, getapplicationlist } from '@/api/message'
import msgcontent from './component/msgcontent.vue'
import peoplecontent from './component/peoplecontent.vue'
import application from './component/application.vue'
import Dialog from '@/components/Dialog'
import addfriend from './component/addfriend.vue'
export default {
  components: {
    people,
    msg,
    msgcontent,
    peoplecontent,
    Dialog,
    addfriend,
    application
  },
  data() {
    return {
      msg: '1111111111',
      socket: null,
      activename: 'msg',
      tabList: [
        {
          name: 'msg',
          url: 'msg',
          active: 'msg-ac'
        },
        {
          name: 'people',
          url: 'people',
          active: 'people-ac'
        },
      ],
      chatList: [],
      chatname: '',
      msgData: {},
      contentone: [],
      allunread: 0,
      groupList: [],
      peopledata: {},
      searchKeyWord: '',
      friendList: [],
      openapplicationvalue: '',
      value1: '',
      notes: '',
      msg: '',
      list: [],
      appunread: 0
    }
  },
  mounted() {
    this.getchatList()
    changeChatState({ UserId: localStorage.getItem('userId'), ChatId: -1 }).then(res => {
      if (res.code === 200) {
      }
    })
    let socket = io('ws://localhost:8080')
    socket.on(localStorage.getItem('userId'), (data) => {
      getChatList({ UserId: localStorage.getItem('userId') }).then(res => {
        if (res.code == 200) {
          this.chatList = res.data
          this.allunread = res.allunread
          this.$store.commit('changeAllunread', res.allunread)
        }
      })
      getChatOne({ UserId: data.sendid, ChatId: data.id }).then(res => {
        if (res.code == 200) {
          this.contentone = res.data
        }
      })
      if (data.sendname && data.sendname == '审批好友') {
        getFriendGroup({ UserId: localStorage.getItem('userId') }).then(res => {
          this.groupList = res.data.map(item => {
            return {
              ...item,
              friendlist: []
            }
          })
          this.value1 = this.groupList[0].group_id
        })
      }
      this.getapplicationlist()
    })

  },
  watch: {
    allunread(val) {
      this.tabList = this.tabList.map(item => {
        if (item.name == 'msg') {
          return {
            ...item,
            allunread: this.allunread
          }
        } else {
          return {
            ...item
          }
        }
      })
    },
    '$store.state.appunread'(value) {
      this.appunread = localStorage.getItem('appunread')
    }
  },
  methods: {
    changeTab(name) {
      this.activename = name
      if (name == 'msg') {
        this.getchatList()
        this.chatname = 'message'
      } else if (name == 'people') {
        this.$refs.people.clearexpandList()
        this.peopledata = {}
        this.chatname = 'people'
        this.getFriendGroup()
      }
    },
    getchatList() {
      getChatList({ UserId: localStorage.getItem('userId') }).then(res => {
        if (res.code == 200) {
          this.chatList = res.data
          this.allunread = res.allunread
          this.$store.commit('changeAllunread', res.allunread)
        }
      })
    },
    changeChat(val) {
      this.msgData = val
      this.chatname = 'message'
      this.getChatOne(this.msgData.that_id)
      changeChatState({ UserId: localStorage.getItem('userId'), ChatId: val.that_id }).then(res => {
        if (res.code === 200) {
        }
      })
      removeUn({ UserId: localStorage.getItem('userId'), ChatId: val.that_id, OpenId: val.open_id }).then(res => {
        if (res.code == 200) {
          this.getchatList()
        }
      })
    },
    changefriend(val) {
      this.chatname = 'people'
      this.groupList = this.groupList.map(item => {
        if (item.group_id == val.group_id) {
          console.log(111);
          return {
            ...item,
            friendlist: item.friendlist.map(_item => {
              if (_item.friend_id == val.friend_id) {
                return {
                  ..._item,
                  open: true,
                }
              } else {
                return {
                  ..._item,
                  open: false,
                }
              }
            })
          }
        } else {
          return {
            ...item,
            friendlist: item.friendlist.map(_item => {
              return {
                ..._item,
                open: false,
              }
            })
          }
        }
      })
      this.peopledata = val
    },
    getChatOne(val) {
      getChatOne({ UserId: localStorage.getItem('userId'), ChatId: val }).then(res => {
        if (res.code == 200) {
          this.contentone = res.data
        }
      })
    },
    async send(val) {
      let res = await sendMsg({
        UserId: localStorage.getItem('userId'),
        ChatId: val.thatid,
        Content: val.content
      })
      let socket = io('ws://localhost:8080')
      socket.emit('aaa', JSON.stringify({
        name: 'aaa',
        id: val.thatid,
        sendid: localStorage.getItem('userId'),
      }))
      if (res.code == 200) {
        this.getChatOne(val.thatid)
        this.getchatList()
      }
    },
    getFriendGroup() {
      getFriendGroup({ UserId: localStorage.getItem('userId') }).then(res => {
        this.groupList = res.data.map(item => {
          return {
            ...item,
            friendlist: []
          }
        })
        this.value1 = this.groupList[0].group_id
      })
    },
    getFriendlist(val) {
      getFriendList({ UserId: localStorage.getItem('userId'), GroupId: val.data.group_id }).then(res => {
        console.log(res);
        if (res.code == 200) {
          this.groupList = this.groupList.map(item => {
            if (item.group_id == val.data.group_id) {
              return {
                ...item,
                friendlist: res.data
              }
            } else {
              return {
                ...item
              }
            }
          })
        }
      })
    },
    async sendmessage(val) {
      let res = await addChat({
        UserId: localStorage.getItem('userId'),
        ChatId: val.that_id,
      })
      if (res.code == 200) {
        getChatList({ UserId: localStorage.getItem('userId') }).then(res => {
          if (res.code == 200) {
            this.chatname = 'message'
            this.activename = 'msg'
            this.chatList = res.data
            this.allunread = res.allunread
            this.$store.commit('changeAllunread', res.allunread)
            this.msgData = this.chatList.find(item => {
              return item.that_id == val.that_id
            })
            getChatOne({ UserId: localStorage.getItem('userId'), ChatId: val.that_id }).then(res => {
              if (res.code == 200) {
                this.contentone = res.data
                this.$refs.msg.select(val.that_id)
              }
            })
          }
        })
      } else {
        this.chatname = 'message'
        this.activename = 'msg'
        this.getChatOne(val.that_id)
        this.msgData = this.chatList.find(item => {
          return item.that_id == val.that_id
        })
        this.$refs.msg.select(val.that_id)
      }
      this.$refs.dialog.close()
    },
    add() {
      this.$refs.dialog.open()
    },
    search() {
      searchFriend({ UserId: localStorage.getItem('userId'), search: this.searchKeyWord }).then(res => {
        this.friendList = res.data
      })
    },
    openapplication(val, name) {
      this.openapplicationvalue = name
      this.openapplicationobj = val
      this.$refs.dialog.close()
      this.$refs.dialog1.open()
      this.getFriendGroup()
      this.notes = ''
      this.msg = ''
    },
    // 申请添加好友
    addfriend() {
      addFriend({
        UserId: localStorage.getItem('userId'),
        GroupId: this.value1,
        ThatId: this.openapplicationobj.that_id,
        appmsg: this.msg,
        notes: this.notes
      }).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '申请成功',
            type: 'success'
          })
          this.$refs.dialog1.close()
          let socket = io('ws://localhost:8080')
          socket.emit('aaa', JSON.stringify({
            name: 'aaa',
            id: this.openapplicationobj.that_id,
            sendid: localStorage.getItem('userId'),
          }))
          if (this.$refs.application) {
            this.$refs.application.getapplicationlist()
          }
        }
      })
    },
    // 打开好友信息列表
    openfriendapplication(val) {
      this.chatname = 'friend'
    },
    // 获取好友申请列表
    getapplicationlist() {
      getapplicationlist({ UserId: localStorage.getItem('userId') }).then(res => {
        if (res.code === 200) {
          this.list = res.data
          localStorage.setItem('appunread', res.unread)
          this.$store.commit('changeAppunread')
        }
      })
    },
    changenotes(val) {
      this.groupList = this.groupList.map(item => {
        if (item.group_id == val.group_id) {
          return {
            ...item,
            friendlist: item.friendlist.map(_item => {
              if (_item.that_id == val.that_id) {
                return {
                  ...val,
                  open: true,
                }
              } else {
                return {
                  ..._item
                }
              }
            })
          }
        } else {
          return {
            ...item
          }
        }
      })
    },
    changeGroup(val, value) {
      this.getFriendGroup()
    }
  },
}
</script>
<style lang="scss" scoped>
.app-speck {
  .speck-box {
    width: 1200px;
    height: 700px;
    background: #fff;
    border-radius: 20px;
    position: relative;
    top: 45%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
  }
  .speck-box-tab {
    width: 50px;
    height: 100%;
    background: transparent;
    border-radius: 20px 0 0 20px;
    border: 2px solid #f5f5f5;
    .avatar {
      display: block;
      width: 35px;
      height: 35px;
      border-radius: 50%;
      margin: 20px auto 0;
    }
  }
  .speck-box-list {
    width: 300px;
    height: 100%;
    display: flex;
    flex-direction: column;
    background: transparent;
  }
  .speck-box-content {
    flex: 1;
    background: transparent;
    border-radius: 0 20px 20px 0;
  }
  .speck-box-list-top {
    width: 100%;
    height: 70px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba($color: #565050, $alpha: 0.2);
    box-sizing: border-box;
  }
  .tab-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
    cursor: pointer;
    .tab-item {
      position: relative;
      .msgicon {
        width: 15px;
        height: 15px;
        background: red;
        border-radius: 50%;
        position: absolute;
        bottom: 8px;
        right: 0px;
        font-size: 12px;
        color: #fff;
        line-height: 15px;
        text-align: center;
      }
    }
  }
  .speck-box-list-content {
    width: 100%;
    height: 100%;
    // background: red;
    border-right: 2px solid #f5f5f5;
  }
  .speck-nohave {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .nohave {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    color: #999;
  }
  .have {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 16px;
    color: #999;
    margin-top: 10px;
    padding: 0 10px;
  }
  :deep(.el-dialog__body) {
    height: 77%;
    display: flex;
    flex-direction: column;
  }
}
</style>